<template>
  <vue-particles
    id="tsparticles"
    @particles-loaded="particlesLoaded"
    :options="options"
  />
  <div class="min-h-screen flex items-center justify-center relative z-10">
    <div class="w-full max-w-md">
      <div class="bg-white rounded-lg p-8 shadow-lg">
        <div :class="cn('flex flex-col gap-6')">
          <form @submit.prevent="handleLogin">
            <div class="flex flex-col gap-6">
              <div class="flex flex-col items-center gap-2">
                <a
                  href="#"
                  class="flex flex-col items-center gap-2 font-medium"
                >
                  <div
                    class="flex size-8 items-center justify-center rounded-md"
                  >
                    <GalleryVerticalEnd class="size-6" />
                  </div>
                  <span class="sr-only">Acme Inc.</span>
                </a>
                <h1 class="text-xl font-bold">欢迎来到智图工坊</h1>
                <div class="text-center text-sm">
                  没有账户？
                  <a
                    href="#"
                    class="underline underline-offset-4"
                    @click="goToRegister"
                  >
                    注册
                  </a>
                </div>
              </div>
              <div class="flex flex-col gap-6">
                <div class="grid gap-3">
                  <Label for="usernameOrEmail">Account</Label>
                  <Input
                    id="usernameOrEmail"
                    v-model="formData.usernameOrEmail"
                    type="text"
                    placeholder="Enter your username or email"
                    required
                  />
                </div>
                <div class="grid gap-3">
                  <Label for="password">Password</Label>
                  <Input
                    id="password"
                    v-model="formData.password"
                    type="password"
                    placeholder="Enter your password"
                    required
                  />
                </div>
                <Button type="submit" class="w-full" :disabled="isLoading">
                  <span v-if="isLoading">登录中...</span>
                  <span v-else>Login</span>
                </Button>
              </div>
              <div
                class="after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"
              >
                <span
                  class="bg-background text-muted-foreground relative z-10 px-2"
                >
                  Or
                </span>
              </div>
              <div class="grid gap-4 sm:grid-cols-2">
                <Button variant="outline" type="button" class="w-full">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path
                      d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"
                      fill="currentColor"
                    />
                  </svg>
                  Continue with Apple
                </Button>
                <Button variant="outline" type="button" class="w-full">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path
                      d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
                      fill="currentColor"
                    />
                  </svg>
                  Continue with Google
                </Button>
              </div>
            </div>
          </form>
          <div
            class="text-muted-foreground *:[a]:hover:text-primary text-center text-xs text-balance *:[a]:underline *:[a]:underline-offset-4"
          >
            By clicking continue, you agree to our
            <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>.
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { GalleryVerticalEnd } from "lucide-vue-next";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { UserService } from "@/api/user";
import { toast } from "vue-sonner";

const particlesLoaded = async (container: any) => {
  console.log("Particles container loaded", container);
};

const options = reactive({
  background: {
    color: {
      value: "#ffffff", // 粒子颜色
    },
  },
  fpsLimit: 60,
  interactivity: {
    events: {
      onClick: {
        enable: true,
        mode: "push", // 可用的click模式有: "push", "remove", "repulse", "bubble"。
      },
      onHover: {
        enable: true,
        mode: "grab", // 可用的hover模式有: "grab", "repulse", "bubble"。
      },
      resize: true,
    },
    modes: {
      bubble: {
        distance: 400,
        duration: 2,
        opacity: 0.8,
        size: 40,
      },
      push: {
        quantity: 4,
      },
      repulse: {
        distance: 200,
        duration: 0.4,
      },
    },
  },
  particles: {
    color: {
      value: "#000",
    },
    links: {
      color: "#000", // '#dedede'。线条颜色。
      distance: 150, // 线条长度
      enable: true, // 是否有线条
      opacity: 0.5, // 线条透明度。
      width: 1, // 线条宽度。
    },
    collisions: {
      enable: false,
    },
    move: {
      direction: "none",
      enable: true,
      outMode: "bounce",
      random: false,
      speed: 4, // 粒子运动速度。
      straight: false,
    },
    number: {
      density: {
        enable: true,
        area: 800,
      },
      value: 80, // 粒子数量。
    },
    opacity: {
      value: 0.5, // 粒子透明度。
    },
    shape: {
      type: "circle", // 可用的粒子外观类型有："circle","edge","triangle", "polygon","star"
    },
    size: {
      random: true,
      value: 5,
    },
  },
  detectRetina: true,
});

const router = useRouter();
const isLoading = ref(false);
const errorMessage = ref("");

const formData = reactive({
  usernameOrEmail: "",
  password: "",
});

// 处理登录
async function handleLogin() {
  isLoading.value = true;
  errorMessage.value = "";

  // 验证用户名或邮箱和密码不为空
  if (!formData.usernameOrEmail.trim()) {
    errorMessage.value = "请输入用户名或邮箱";
    isLoading.value = false;
    return;
  }

  if (!formData.password.trim()) {
    errorMessage.value = "请输入密码";
    isLoading.value = false;
    return;
  }

  try {
    // 调用登录接口
    const response = await UserService.login({
      usernameOrEmail: formData.usernameOrEmail,
      password: formData.password,
    });

    if (response.success) {
      // 保存登录状态
      UserService.saveToken(response.data.token);
      UserService.saveUserInfo(response.data.userInfo);

      toast.success("登录成功");
      console.log("登录成功:", response.data);

      // 跳转到主页
      router.push("/");
    } else {
      errorMessage.value = response.message || "登录失败，请重试";
      toast.error(errorMessage.value);
    }
  } catch (error) {
    errorMessage.value = "登录失败，请重试";
    console.error("登录错误:", error);
    toast.error(errorMessage.value);
  } finally {
    isLoading.value = false;
  }
}

// 跳转到注册页面
function goToRegister() {
  router.push("/register");
}
</script>
